package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@Slf4j
@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        String[] urls=new String[]{"/user/sendMsg","/user/login","/employee/login","employee/logout","/login.html","/api/","/images/","/js/","/plugins/","/styles/"};
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;
        String uri = req.getRequestURI();
        Long id = (Long) req.getSession().getAttribute("empId");
        if (id!=null){
            BaseContext.setId(id);
            chain.doFilter(request, response);
            return;
        }

        for (String url : urls) {
            if (uri.contains(url)){
                chain.doFilter(request, response);
                return;
            }
        }

        Long user = (Long) req.getSession().getAttribute("userId");

        if (user!=null){
            BaseContext.setId(user);
            chain.doFilter(request, response);
            return;
        }


        resp.setContentType("application/json;charset=utf-8");
        String notlogin = JSON.toJSONString(R.error("NOTLOGIN"));
        resp.getWriter().write(notlogin);
        return;

    }
}
